package xwebsocket

import (
	"net/http"
	"net/url"
	"time"

	"gitee.com/lihaiping1603/utils/log"
	"github.com/gorilla/websocket"
)

func WebsocketDial(urlstr string, handler WebsocketHandler) (*WebsocketSession, error) {
	u, err := url.Parse(urlstr)
	if err != nil {
		log.Error("url:%s parse failed, err=%s", urlstr, err.Error())
		return nil, err
	}
	socket := &websocket.Dialer{
		Proxy:            http.ProxyFromEnvironment,
		HandshakeTimeout: 10 * time.Second,
	}
	conn, response, err := socket.Dial(urlstr, nil)
	if err != nil {
		log.Error("WebSockClient Dial url:%s failed, err=%s", urlstr, err.Error())
		return nil, err
	}
	session := smgr.newWebsocketSession(conn, handler)
	session.header = response.Header
	session.uri = u.RequestURI()
	if handler != nil {
		handler.OnConnected(session)
	}
	go session.readCycle()
	return session, nil
}
